package com.swsc.xapp.offline.lhttpd;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.yanzhenjie.andserver.AndServer;
import com.yanzhenjie.andserver.Server;

import java.net.InetAddress;
import java.util.concurrent.TimeUnit;

public class AndHttpService extends Service {
    private Server mServer;

    @Override
    public void onCreate() {
        mServer = AndServer.webServer(this)
                .port(48888)
                .timeout(60, TimeUnit.SECONDS)
                .listener(new Server.ServerListener() {
                    @Override
                    public void onStarted() {
//                        InetAddress address = NetUtils.getLocalIPAddress();
                        AndServerManager.onServerStart(AndHttpService.this, "localhost");
                    }

                    @Override
                    public void onStopped() {
                        AndServerManager.onServerStop(AndHttpService.this);
                    }

                    @Override
                    public void onException(Exception e) {
                        android.util.Log.e("AndServer", e.getMessage(), e);
                        AndServerManager.onServerError(AndHttpService.this, e.getMessage());
                    }
                })
                .build();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startServer();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        stopServer();
        super.onDestroy();
    }

    /**
     * Start server.
     */
    private void startServer() {
        mServer.startup();
    }

    /**
     * Stop server.
     */
    private void stopServer() {
        mServer.shutdown();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
